package com.lmabbe.oauth.service;

import cn.hutool.core.bean.BeanUtil;
import com.lmabbe.common.global.context.session.JwtUser;
import com.lmabbe.common.global.context.session.LoginUser;
import com.lmabbe.common.global.enums.DataScopeEnum;
import com.lmabbe.core.common.entitys.SysRole;
import com.lmabbe.core.common.entitys.SysUser;
import com.lmabbe.core.common.interfaces.SysUserService;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author lmabbe
 */
@Service
@RequiredArgsConstructor
public class UserDetailServiceImpl implements UserDetailsService {

    @DubboReference()
    private SysUserService sysUserService;

    /**
     * 根据用户名加载用户
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = sysUserService.findByUserAccount(username);
        if (user == null) {
            throw new UsernameNotFoundException(String.format("用户%s不存在", username));
        }
        JwtUser jwtUser = new JwtUser();
        SysRole userRole = sysUserService.getUserRole(user.getUserId());
        LoginUser loginUser = BeanUtil.copyProperties(user, LoginUser.class);
        loginUser.setDataScope(DataScopeEnum.byCode(userRole.getDataScope()));
        loginUser.setCustomDataScope(userRole.getCustomDataScope());
        jwtUser.setLoginUser(loginUser);
        return jwtUser;
    }

    /**
     * 根据电话号码加载用户
     *
     * @param mobile
     * @return
     * @throws UsernameNotFoundException
     */
    public UserDetails loadUserByMobile(String mobile) throws UsernameNotFoundException {
        SysUser user = sysUserService.findByUserMobile(mobile);
        if (user == null) {
            throw new UsernameNotFoundException(String.format("手机号%s不存在", mobile));
        }
        JwtUser jwtUser = new JwtUser();
        jwtUser.setLoginUser(BeanUtil.copyProperties(user, LoginUser.class));
        return jwtUser;
    }

    /**
     * 根据第三方平台登录用户
     *
     * @param identification
     * @return
     * @throws UsernameNotFoundException
     */
    public UserDetails loadUserByThirdPlatformIdentification(String identification) throws UsernameNotFoundException {
        SysUser user = sysUserService.findByUserAccount(identification);
        if (user == null) {
            throw new UsernameNotFoundException(String.format("用户%s不存在", identification));
        }
        JwtUser jwtUser = new JwtUser();
        jwtUser.setLoginUser(BeanUtil.copyProperties(user, LoginUser.class));
        return jwtUser;
    }
}
